package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired(required = false)
    private SetmealMapper setmealMapper;
    @Autowired(required = false)
    private SetmealDishMapper setmealDishMapper;
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    //保存新增套餐菜品信息
    @Override
    @Transactional//开始事务管理
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void save(SetmealDto setmealDto) {
        //补全Setmeal信息，比如创建修改时间
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setUpdateTime(LocalDateTime.now());
        //调用保存方法
        setmealMapper.save(setmealDto);//把套餐的id设置给实体类
        //得到套餐菜品，补全菜品信息(setmeal_id 、修改、创建时间、排序，)
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
            setmealDish.setCreateTime(LocalDateTime.now());
            setmealDish.setUpdateTime(LocalDateTime.now());
            setmealDish.setSort(0);
            return setmealDish;

        }).collect(Collectors.toList());
        //批量插入菜品表
        setmealDishMapper.saveBatch(setmealDishes);
    }

    /**
     * 作用：展示套餐列表
     *
     * @param page     当前页
     * @param pageSize 页面大小
     * @param name     菜品的名称
     * @return
     */
    @Override
    public Page<SetmealDto> findByPage(Integer page, Integer pageSize, String name) {
        //1. 设置当前页与页面大小
        PageHelper.startPage(page, pageSize);
        //2. 根据name查询数据，得到List集合  List<Setmeal>  select * from setmeal
        List<Setmeal> setmealList = setmealMapper.findByName(name);
        //3. 创建PageInfo对象,创建PageInfo对象了
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealList);
        //4. 遍历List<Setmeal> ,把Setmeal转换为SetmealDto
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (Setmeal setmeal : pageInfo.getList()) {
            //每个setmaal都对应一个SetmealDto
            SetmealDto setmealDto = new SetmealDto();
            //拷贝属性
            BeanUtils.copyProperties(setmeal, setmealDto);
            //查找套餐类别
            Category category = categoryMapper.findById(setmeal.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            setmealDtoList.add(setmealDto);
        }
        //创建page对象
        Page<SetmealDto> pageResult = new Page<>(setmealDtoList, pageInfo.getTotal(), page, pageSize);
        return pageResult;
    }

    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void DeleteByIds(List<Long> ids) {
        //检查套餐里是否有在售商品，如果有，直接抛异常
        Long count = setmealMapper.queryDishWithStatus(ids);
        if (count > 0) {
            throw new CustomException("存在在售商品，无法删除");
        }
        //如果选中都是停售，泽可以删除
        setmealMapper.DeleteByIds(ids);
        //删除套餐里的菜品
        setmealDishMapper.deleteBySetmealIds(ids);
    }

    /**
     * 根据套餐的类别展示套餐
     *
     * @param categoryId
     * @param status
     * @return
     */
    @Override
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    public List<Setmeal> list(long categoryId, Integer status) {
        return setmealDishMapper.list(categoryId, status);

    }
    /*批量起售停售套餐*/
    @Override
    public void statusByIds(List<Long> ids, Integer status) {
        setmealMapper.UpdateStatusByIds(ids,status);
    }


    /*回显数据*/
    @Override
    public SetmealDto findBySetmealId(Long id) {
        /*根据id查找套餐*/
        Setmeal setmeal=  setmealMapper.findBySetmealId(id);
         List<SetmealDish> setmealDishList=  setmealDishMapper.findBySetmealId(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(setmealDishList);
        return setmealDto;
    }
    //*根据id修改套餐*//
    @Override
    @Transactional
    public void UpDateSetmealById( SetmealDto setmealDto) {
        //补全修改时间
        setmealDto.setUpdateTime(LocalDateTime.now());
        //创建集合 返回集合类型
        List<Long> longList = new ArrayList<>();
        longList.add(setmealDto.getId());
        //删除套菜菜品信息
        setmealDishMapper.deleteBySetmealIds(longList);
        //修改菜品
        setmealMapper.updateById(setmealDto);
        //补全菜品口味并重新插入
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(setmealDish -> {
            //补充元素
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setCreateTime(LocalDateTime.now());
            setmealDish.setUpdateTime(LocalDateTime.now());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setSort(0);
            return setmealDish;
        }).collect(Collectors.toList());
          /*批量保存口味信息*/
        setmealDishMapper.saveBatch(setmealDishes);

    }
}
